import os
import shutil

def restructure_folders(input_folder, output_folder):
    # 确保输出文件夹存在
    os.makedirs(output_folder, exist_ok=True)

    # 遍历输入文件夹的所有文件和子文件夹
    for root, dirs, files in os.walk(input_folder):
        for dir_name in dirs:
            # 当前文件夹路径
            current_folder_path = os.path.join(root, dir_name)
            
            # 检查是否是复合命名的文件夹（例如 002_003）
            if "_" in dir_name:
                sub_folders = dir_name.split("_")  # 分拆为多个子文件夹
                for sub_folder in sub_folders:
                    # 创建子文件夹对应的目录
                    target_folder = os.path.join(output_folder, sub_folder)
                    os.makedirs(target_folder, exist_ok=True)
                    
                    # 将复合文件夹中的内容复制到目标子文件夹
                    for item in os.listdir(current_folder_path):
                        source_path = os.path.join(current_folder_path, item)
                        target_path = os.path.join(target_folder, item)
                        
                        if os.path.isfile(source_path):  # 只复制文件
                            shutil.copy2(source_path, target_path)
            else:
                # 如果是普通文件夹，直接复制文件到目标文件夹
                target_folder = os.path.join(output_folder, dir_name)
                os.makedirs(target_folder, exist_ok=True)
                for item in os.listdir(current_folder_path):
                    source_path = os.path.join(current_folder_path, item)
                    target_path = os.path.join(target_folder, item)
                    
                    if os.path.isfile(source_path):  # 只复制文件
                        shutil.copy2(source_path, target_path)

# 输入文件夹路径和输出文件夹路径
input_folder = r"D:\GRWJ\OBS\HUST-OBC-main\HUST-OBC\deciphered"  # 图一的文件夹路径
output_folder = "train"  # 图二的文件夹路径

# 调用函数
restructure_folders(input_folder, output_folder)
